package com.wevolution.controller;
import cn.tiandechain.jbcc.bean.DataBuilder;
import cn.tiandechain.jbcc.bean.QueryResult;
import cn.tiandechain.jbcc.message.JBCCResult;
import cn.tiandechain.jbcc.message.RegulationType;
import cn.tiandechain.jbcc.message.Transaction;
import cn.tiandechain.jbcc.util.BCKeyStoreUtil;
import com.alibaba.fastjson.JSON;
import com.tiande.jbcc.clien.JBCCClien;
import com.wevolution.common.utils.DateUtil;
import com.wevolution.common.utils.ResponseUtil;
import com.wevolution.common.utils.StringUtil;
import com.wevolution.domain.*;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import com.wevolution.ipchain.ConnectionManager;
import com.wevolution.mapper.WorksInfoMapper;
import com.wevolution.mapper.WorksMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.constraints.Null;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CountDownLatch;

public class Main {
    @Resource
    private WorksMapper worksMapper;
//    static CountDownLatch c = new CountDownLatch(2);
    public void main(String[] argv) {
        selectBlockWorksInfo("83","456317c1bbf686893a309a9cbb399420");
        /*WorksInfo stu=new WorksInfo();
        stu.setWorksName("JSON");
        List<WorksInfo> lists = new ArrayList<>();
        lists.add(stu);
        //1、使用JSONObject
//        JSONObject json = JSONObject.fromObject(lists);
        JSONArray array= JSONArray.fromObject(lists);
        String strJson=array.toString();


        //2、使用JSONArray
        JSONArray jsonArray=JSONArray.fromObject(strJson);
        //获得jsonArray的第一个元素
//        Object o=jsonArray.get(0);
//        JSONObject jsonObject2=JSONObject.fromObject(o);
        List<WorksInfo> stu2=(List<WorksInfo>)JSONObject.toBean(jsonArray, Student.class);*/

        //1、使用JSONObject
//        JSONObject jsonObject=JSONObject.fromObject(strJson);
//        Student stus=(Student)JSONObject.toBean(jsonObject, Student.class);
//        System.out.println("stu:"+stus);

        /*final CountDownLatch latch = new CountDownLatch(1);
        Works works = new Works();
        works.setProgress(1);
        works.setWorksName("测试");
        String jsonObject = "";
        // 创建Httpclient对象
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        httpClient.start();
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost("http://localhost/works/sampleApi");
        //给httpPost设置JSON格式的参数
        StringEntity requestEntity = new StringEntity(jsonObject, "UTF-8");
        requestEntity.setContentEncoding("UTF-8");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(requestEntity);
        // 执行http请求
        httpClient.execute(httpPost, new FutureCallback<HttpResponse>() {

            public void completed(final HttpResponse response) {
                try {
                    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println(" response content is : " + content);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                close(httpClient);
                latch.countDown();
            }

            public void failed(final Exception ex) {
                System.out.println(httpPost.getRequestLine() + "->" + ex);
                close(httpClient);
                latch.countDown();
            }

            public void cancelled() {
                System.out.println(httpPost.getRequestLine() + " cancelled");
                close(httpClient);
                latch.countDown();
            }

        });
        System.out.println("12345");
        latch.await();
        System.out.println("123cancelled");
        System.out.println("456cancelled");*/
//        String s = selectBlockWorksInfo("38","cc4b21244dfc46e08e83da457edc1d25");
//        System.out.println(s);
    }

    private static String selectBlockWorksInfo(String blockId, String worksId) {
        String value = "tcp://ec2-54-222-155-229.cn-north-1.compute.amazonaws.com.cn:61616?,tcp://ec2-52-80-61-50.cn-north-1.compute.amazonaws.com.cn:61616?,tcp://ec2-54-223-75-107.cn-north-1.compute.amazonaws.com.cn:61616?,tcp://ec2-54-223-138-92.cn-north-1.compute.amazonaws.com.cn:61616?";
        String[] nodeMqTcps = value.split(",");
        JBCCClien jbccClient = new JBCCClien();
        jbccClient.startClien("admin_1", nodeMqTcps, "ipmanagermq", "ipblockchain798");
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("block_id", blockId);
        conditionMap.put("opus_id", worksId);
        QueryResult queryResult = null;
        try {
            queryResult = jbccClient.selectBlockWorksInfo("tdbc", conditionMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (queryResult != null) {
            JBCCResult result = queryResult.getJbccResult();
            String errorCode = result.getErrorCode();
            if ("0".equals(errorCode)) {// 交易执行成功
                List<Map<String, Object>> resultlist = queryResult.getResultlist();
                if (!resultlist.isEmpty()) {
                    Map<String, Object> map = resultlist.get(0);
                    return JSON.toJSONString(map);
                } else {
                    return "";
                }
            }
        }
        return "";
    }

    private static void close(CloseableHttpAsyncClient client) {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String sendMsgApi() {
		BCKeyStoreUtil.createKeyStore("admin_1", "123", "block_chain_user");
        JBCCClien connection = ConnectionManager.getConnection();
        String outerSerial = UUID.randomUUID().toString().substring(0, 32);
        String reqNo = outerSerial.substring(outerSerial.length() - 5, outerSerial.length() - 1);
        JBCCResult r = null;
        List<DataBuilder> dataList = new ArrayList<DataBuilder>();
        // works
        DataBuilder dataBuilderworks = new DataBuilder("tdbc", "workzhang", "n", outerSerial);
        Map<String, String> worksMap = worksMapper.queryWorksById("8eef7dc5f4634acebc931bc500f6496d");
        worksMap.put("req_no", reqNo);
        dataBuilderworks.setParamMap(worksMap);
        Transaction tran = new Transaction();
        tran.setRegulationType(RegulationType.REGULATION_ORIGINAL_SAVE);
        dataBuilderworks.setTransaction(tran);
        dataList.add(dataBuilderworks);

        int status = 4;
        try {
            r = connection.sendAndCountReturnForIPBlockChain(dataList);
            if("0".equals(r.getErrorCode())){
                if(StringUtil.isEmpty(r.getBlockId())){
                    status = 4;
                    throw new RuntimeException("返回blockId异常");
                }else{
                    status = 2;
                }
            }else if("TDBC3009".equals(r.getErrorCode())){
                status = 4;
            }else{
                status = 3;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = 4;
        }finally {
            ConnectionManager.closeConnection();
        }
        return ResponseUtil.getResponseJson(0, status+"",r);
    }
}
